﻿using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Linq;
using System.Windows.Forms;

namespace CloudShot.Controls
{
  public partial class ColorSelectControl : UserControl
  {
    private const int DefaultColorsInRow = 7;

    [DefaultValue("ColorSelectControl")]
    public string LabelText
    {
      get { return label.Text; }
      set { label.Text = value; }
    }

    [DefaultValue(DefaultColorsInRow)]
    public int ColorsInRow { get; set; }

    public IEnumerable<ColorRadioButton> ColorRadioButtons
    {
      get { return tableLayoutPanel.Controls.OfType<ColorRadioButton>(); }
    }

    public ColorSelectControl()
    {
      InitializeComponent();

      tableLayoutPanel.Margin = Padding.Empty;
      tableLayoutPanel.AutoSize = true;
      tableLayoutPanel.AutoSizeMode = AutoSizeMode.GrowAndShrink;
      ColorsInRow = DefaultColorsInRow;
    }

    public void ApplyPalettes(IEnumerable<Color> colors)
    {
      tableLayoutPanel.SuspendLayout();
      tableLayoutPanel.Controls.Clear();

      int count = 0;

      foreach (Color color in colors)
      {
        var radioButton = new ColorRadioButton
        {
          Appearance = Appearance.Button,
          Color = color,
          FlatStyle = FlatStyle.Flat,
          Width = 24,
          Height = 24,
          Margin = Padding.Empty,
          Padding = new Padding(4)
        };

        int colorsInRow = ColorsInRow > 0 ? ColorsInRow : DefaultColorsInRow;

        int row = count / colorsInRow;
        int col = count % colorsInRow;

        tableLayoutPanel.Controls.Add(radioButton, col, row);

        count++;
      }

      tableLayoutPanel.ResumeLayout(true);
    }
  }
}